package Thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-08-11
 * Time: 10:51
 */
public class demo35 {
    private static int result;

    public static void main1(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            int sum = 0;
            for (int i = 0; i < 1000; i++) {
                sum += i;
            }
            result = sum;
        });
        t1.start();
        t1.join();
        System.out.println(result);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //泛型参数表示返回值的类型
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 0; i < 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };//此时直接可以返回sum,不需要额外创建变量

        //Thread不能直接传callable参数,只能借助FutureTask
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread t = new Thread(futureTask);

        t.start();
        System.out.println(futureTask.get());//通过FutureTask拿到结果
    }
}
